package com.mind.adjust.controller;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.listener.ReadListener;
import com.mind.common.utils.poi.ExcelUtil;
import com.mind.common.utils.poi.ImportExcelResult;
import com.mind.common.utils.poi.ValidationUtils;
import com.mind.system.domain.AjBussinessGroup;
import com.mind.adjust.service.AjBussinessGroupService;
import com.mind.common.web.controller.BaseController;
import com.mind.common.core.domain.AjaxResult;
import com.mind.common.web.page.TableDataInfo;
import com.mind.common.log.annotation.Log;
import com.mind.common.log.enums.BusinessType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.ConstraintViolation;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 智能审核模块/审核模块/业务组别管理
 *
 * @author makejava
 * @DocView.PathPrefix {{host}}/api/adjust
 * @since 2024-08-01 18:16:11
 */
@RestController
@RequestMapping("adjust/bussinessGroup")
public class AjBussinessGroupController extends BaseController {
    /**
     * 服务对象
     */
    @Autowired
    private AjBussinessGroupService ajBussinessGroupService;

    /**
     * 获取业务组别列表
     *
     * @param bussinessGroup 筛选条件
     * @return com.mind.system.domain.AjBussinessGroup
     */
//    @RequiresPermissions("adjust:bussinessGroup:list")
    @Log(title = "业务组别列表", businessType = BusinessType.QUERY)
    @GetMapping("/list")
    public TableDataInfo list(AjBussinessGroup bussinessGroup)
    {
        startPage();
        List<AjBussinessGroup> list = ajBussinessGroupService.selectBussinessGroupList(bussinessGroup);
        return getDataTable(list);
    }
    
    /**
     * 业务组别导入
     *
     * @return 结果
     */
//    @RequiresPermissions("adjust:bussinessGroup:import")
    @Log(title = "业务组别导入", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importExcel(MultipartFile file) throws IOException {
        List<AjBussinessGroup> cachedDataList = new ArrayList<>();
        List<ImportExcelResult> errorList = new ArrayList<>();
        EasyExcel.read(file.getInputStream(), AjBussinessGroup.class, new ReadListener<AjBussinessGroup>() {

            @Override
            public void invoke(AjBussinessGroup data, AnalysisContext context) {
                Set<ConstraintViolation<AjBussinessGroup>> violations = ValidationUtils.getValidator().validate(data);
                if(violations.size() > 0){
                    throw new ExcelDataConvertException(context.readRowHolder().getRowIndex(), 0, null, null, "");
                }
                cachedDataList.add(data);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                saveData();
            }

            /**
             * 加上存储数据库
             */
            private void saveData() {
                int i = ajBussinessGroupService.batchInsert(cachedDataList);
            }

            /**
             * 在转换异常 获取其他异常下会调用本接口。抛出异常则停止读取。如果这里不抛出异常则 继续读取下一行。
             *
             * @param exception
             * @param context
             * @throws Exception
             */
            @Override
            public void onException(Exception exception, AnalysisContext context) {
                // 如果是某一个单元格的转换异常 能获取到具体行号
                // 如果要获取头的信息 配合invokeHeadMap使用
                if (exception instanceof ExcelDataConvertException) {
                    ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception;
                    String errMsg = String.format("第%d行数据验证异常", excelDataConvertException.getRowIndex());
                    errorList.add(new ImportExcelResult(){{
                        setRow(excelDataConvertException.getRowIndex());
                        setCol(excelDataConvertException.getColumnIndex());
                        setError(errMsg);
                    }});
                }
            }
        }).sheet().doRead();
        if(errorList.size() > 0) {
            return AjaxResult.success(String.format("一共%d条，成功导入%d条，错误%d条。错误详情：%s", cachedDataList.size() + errorList.size(), cachedDataList.size(), errorList.size(), errorList.stream().map(ImportExcelResult::getError).collect(Collectors.joining("\r\n"))));
        }else{
            return AjaxResult.success(String.format("一共%d条，成功导入%d条，错误0条。", (cachedDataList.size()), cachedDataList.size()));
        }
    }

    /**
     * 附件类型下载模板
     * @return 结果
     */
    @Log(title = "业务组别下载模板", businessType = BusinessType.DOWNLOAD)
//    @RequiresPermissions("adjust:attachType:download")
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<AjBussinessGroup> util = new ExcelUtil<>(AjBussinessGroup.class);
        String fileName =  URLEncoder.encode("业务组别模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        util.exportExcel(response, new ArrayList<>(), "业务组别数据");
    }
    
    /**
     * 业务组别导出
     * @param bussinessGroup 筛选条件
     * @return 结果
     */
    @Log(title = "业务组别导出", businessType = BusinessType.EXPORT)
//    @RequiresPermissions("adjust:bussinessGroup:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, AjBussinessGroup bussinessGroup)
    {
        List<AjBussinessGroup> list = ajBussinessGroupService.selectBussinessGroupList(bussinessGroup);
        ExcelUtil<AjBussinessGroup> util = new ExcelUtil<AjBussinessGroup>(AjBussinessGroup.class);
        util.exportExcel(response, list, "业务组别数据");
    }

    /**
     * 根据ID获取业务组别详情
     * @return com.mind.system.domain.AjBussinessGroup
     */
//    @RequiresPermissions("adjust:bussinessGroup:query")
    @GetMapping(value = "/{bussinessGroupId}")
    public AjaxResult getInfo(@PathVariable Long bussinessGroupId)
    {
        return success(ajBussinessGroupService.selectBussinessGroupById(bussinessGroupId));
    }

    /**
     * 新增业务组别
     * @return 结果
     */
//    @RequiresPermissions("adjust:bussinessGroup:add")
    @Log(title = "业务组别新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody AjBussinessGroup bussinessGroup)
    {
        return toAjax(ajBussinessGroupService.insertBussinessGroup(bussinessGroup));
    }

    /**
     * 修改业务组别
     * @return 结果
     */
//    @RequiresPermissions("adjust:bussinessGroup:edit")
    @Log(title = "业务组别修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody AjBussinessGroup bussinessGroup)
    {
        return toAjax(ajBussinessGroupService.updateBussinessGroup(bussinessGroup));
    }

    /**
     * 删除业务组别
     * @return 结果
     */
//    @RequiresPermissions("adjust:bussinessGroup:remove")
    @Log(title = "业务组别删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{bussinessGroupIds}")
    public AjaxResult remove(@PathVariable Long[] bussinessGroupIds)
    {
        return toAjax(ajBussinessGroupService.deleteBussinessGroupByIds(bussinessGroupIds));
    }

}


